package indi.woniu.security.handler;

import indi.woniu.entity.ResponseEntity;
import indi.woniu.field.StatusCode;
import indi.woniu.utils.JwtUtils;
import indi.woniu.utils.Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: GaN601
 * @Date: 2021/12/8 15:38
 * @Description:
 */
@Configuration
public class AuthenticationSuccessHandler implements org.springframework.security.web.authentication.AuthenticationSuccessHandler {
    
    @Autowired
    private JwtUtils jwtUtils;
    
    @Override
    public void onAuthenticationSuccess(final HttpServletRequest request, final HttpServletResponse response,
            final Authentication authentication) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        String jwt = jwtUtils.createJwt(authentication.getName());
        response.getWriter().write(
                Util.toJsonStr(
                        new ResponseEntity<>(StatusCode.OK, "OK", jwt)));
    }
}
